package com.keba.lamp.complaint.strategy.impl;

import com.keba.lamp.common.constant.AppendixType;
import com.keba.lamp.complaint.enumeration.MimeEnum;
import com.keba.lamp.complaint.strategy.AbstractCaseFileStrategy;
import com.keba.lamp.complaint.strategy.domain.CaseDownloadParam;
import com.keba.lamp.complaint.strategy.domain.CaseDownloadResult;
import com.keba.lamp.complaint.vo.result.CaseFileResultVO;
import com.keba.lamp.complaint.vo.result.CaseResultVO;
import com.keba.lamp.file.entity.File;
import com.keba.lamp.file.vo.param.FileUploadVO;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 代理人代理手续和证明文件下载
 */
@Slf4j
@RequiredArgsConstructor
@Service
@Getter
@Setter
public class AgentIdentityMaterialFileStrategy extends AbstractCaseFileStrategy {

    @Override
    public CaseDownloadResult exec(CaseDownloadParam param) throws Exception {
        CaseResultVO caseResultVO = caseService.getCaseById(param.getCaseId());
        List<CaseFileResultVO> plaintffAgentFileList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(caseResultVO.getPlaintffAgentResultVOList())) {
            caseResultVO.getPlaintffAgentResultVOList().stream().filter(agentResultVO ->
                    CollectionUtils.isNotEmpty(agentResultVO.getFileList())
            ).forEach(agentResultVO -> {
                plaintffAgentFileList.addAll(agentResultVO.getFileList());
            });
        }
        //委托代理人手续和身份证明
        ByteArrayOutputStream outputStream = pdfCommonService.createFileZip(plaintffAgentFileList);
        if (Objects.nonNull(outputStream)) {
            FileUploadVO fileUploadVO = new FileUploadVO();
            fileUploadVO.setBizType(AppendixType.Download.DOWNLOAD__IDENTITY__MATERIAL);
            fileUploadVO.setContentType(MimeEnum.ZIP.getContentType());
            String caseName = StringUtils.isBlank(caseResultVO.getCaseName()) ? "" : caseResultVO.getCaseName();
            String fileName = caseName + "委托代理人手续和身份证明.zip";
            File file = fileContext.upload(outputStream.toByteArray(), fileName, fileUploadVO);
            return CaseDownloadResult.builder().url(file.getUrl()).build();
        } else {
            return CaseDownloadResult.builder().build();
        }


    }
}
